<?php
/**
 * Created by PhpStorm.
 * User: deng
 * Date: 2015/3/4
 * Time: 16:04
 */

namespace Serve\Controller;

use Common\Controller\NormalApiController;
use Serve\Utils\UserMail;

class MailController extends NormalApiController
{
    /**
     * 检查数据库该用户是否存在，
     * 若不存在，返回404
     * 若存在，但已认证返回403
     * 若存在，且未认证，则发送邮件，成功后返回200
     */
    public function user()
    {
        $username = $this->_request['username'];
        $model = $this->_db->users;
        if ($user = $model->findUnique(['auth.username' => $username])) {
            if ($user['role'] != 0)
                ClientError('已经通过认证', C('CODE.FORBIDDEN')['code']);
            else {
                $result['username'] = $user['auth']['username'];
                $result['role'] = $user['role'];
                $result['userId'] = $user['id'];
                if (UserMail::sendVerifyEmail($username, \JWT::encode($result, C('JWT.key'))))
                    Success(200, '邮箱已发送');
                else
                    ServerError('发送邮件失败，请重新尝试');
            }
        } else {
            ClientError('用戶名不存在', C('CODE.NOT_FOUND')['code']);
        }
    }

    /**
     * 检查数据库用户是否存在，
     * 不存在返回404
     * 存在则发送邮件，成功后返回200
     */
    public function password()
    {
        $username = $this->_request['username'];
        $model = $this->_db->users;
        if ($user = $model->findUnique(['auth.username' => $username])) {
            if ($user['role'] == 0)
                ClientError('未通过邮箱验证', C('CODE.FORBIDDEN')['code']);
            else {
                $result['username'] = $user['auth']['username'];
                $result['role'] = $user['role'];
                $result['userId'] = $user['id'];
                if (UserMail::sendResetPasswordEmail($username, \JWT::encode($result, C('JWT.key'))))
                    Success(200, '邮箱已发送');
                else
                    ServerError('发送邮件失败');
            }
        } else {
            ClientError('用戶名不存在', C('CODE.NOT_FOUND')['code']);
        }
    }
}